package com.sky.robot.frame.controller;

import com.sky.robot.commons.utils.Result;
import com.sky.robot.frame.utils.JSONUtil;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

@RestController("/core/gpt")
public class SkyGptController {

    @PostMapping("/send")
    public Result<?> sendPrompt(@RequestBody Map<String, Object> promptMap){
        return Result.success(send(promptMap));
    }


    private String send(Map<String, Object> promptMap){
        String apiEndpoint = "https://api.openai.com/v1/chat/completions";
        String apiKey = "sk-XelpeD1K6Q5o9GjxfppXLF2alR8aZeThffX4W6gTqJslYIDy"; // 请替换为你的API密钥

        try {
            URL url = new URL(apiEndpoint);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置请求头
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Bearer " + apiKey);
            conn.setRequestProperty("Content-Type", "application/json");
            // 设置请求体
            String data = JSONUtil.map2String(promptMap);
            // String data = `{"prompt": "What is the weather like today?", "max_tokens": 50}`
            conn.setDoOutput(true);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(data.getBytes());
            outputStream.flush();
            // 发送请求并获取响应
            int responseCode = conn.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()
            ));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            // 处理响应
            if (responseCode == 200) {
                System.out.println("响应结果：" + response.toString());
                return response.toString();
                // 在这里对响应进行进一步处理
            } else {
                System.out.println("调用ChatGPT接口失败，HTTP状态码：" + responseCode);
            }
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "处理失败";
    }
}

